package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.*;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.content.service.CourseMarketService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description: // 类说明，在创建类时要填写
 * @ClassName: CourseBaseInfoServiceImpl    // 类名，会自动填充
 * @Author: MYH          // 创建者
 * @Date: 2023/1/28 22:09   // 时间
 * @Version: 1.0     // 版本
 */
@Service
@Slf4j
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {


    @Resource
    private CourseBaseMapper courseBaseMapper;

    @Resource
    private CourseMarketMapper courseMarketMapper;

    @Resource
    private CourseCategoryMapper courseCategoryMapper;

    @Autowired
    private CourseMarketService courseMarketService;

    @Autowired
    private CourseTeacherMapper courseTeacherMapper;

    @Autowired
    private TeachplanMapper teachplanMapper;

    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper;

    /**
     * 课程查询
     * @param params 分页参数
     * @param queryCourseParamsDto 查询条件
     * @return
     */
    @Override
    public PageResult<CourseBase> queryCourseBaseList(PageParams params, QueryCourseParamsDto queryCourseParamsDto) {

        //分页构造器
        Page<CourseBase> page = new Page<>(params.getPageNo(), params.getPageSize());

        //条件构造器
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()),CourseBase::getName,queryCourseParamsDto.getCourseName());
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()),CourseBase::getAuditStatus,queryCourseParamsDto.getAuditStatus());
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()),CourseBase::getStatus,queryCourseParamsDto.getPublishStatus());

        //分页查询  E page 分页参数, @Param("ew") Wrapper<T> queryWrapper 查询条件
        Page<CourseBase> courseBasePage = courseBaseMapper.selectPage(page, queryWrapper);
        List<CourseBase> records = courseBasePage.getRecords();
        long total = courseBasePage.getTotal();

        //返回数据 List<T> items, long counts, long page, long pageSize
        PageResult<CourseBase> pageResult = new PageResult<CourseBase>(records,total, params.getPageNo(), params.getPageSize());
        return pageResult;
    }


    /**
     * 新增课程
     * @param companyId 培训机构的id
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto dto) {

//        //对参数进行合法性的校验
//        if (StringUtils.isBlank(dto.getName())) {
//            XueChengPlusException.cast("课程名称为空");
//        }
//        if (StringUtils.isBlank(dto.getMt())) {
//            XueChengPlusException.cast("课程分类为空");
//        }
//        if (StringUtils.isBlank(dto.getSt())) {
//            XueChengPlusException.cast("课程分类为空");
//        }
//        if (StringUtils.isBlank(dto.getGrade())) {
//            XueChengPlusException.cast("课程等级为空");
//        }
//        if (StringUtils.isBlank(dto.getTeachmode())) {
//            XueChengPlusException.cast("教育模式为空");
//        }
//        if (StringUtils.isBlank(dto.getUsers())) {
//            XueChengPlusException.cast("适应人群为空");
//        }
//        if (StringUtils.isBlank(dto.getCharge())) {
//            XueChengPlusException.cast("收费规则为空");
//        }
        //校验如果课程为收费，价格必须输入
//        String charge = dto.getCharge();
//        if (charge.equals("201001")){//收费
//            if ((StringUtils.isBlank(dto.getPrice() + "") || dto.getPrice() == 0)){
//                XueChengPlusException.cast("此课程为收费，但是价格为空");
//                //throw new RuntimeException("有误");
//            }
//        }

        //对数据进行封装，调用mapper进行持久化
        CourseBase courseBase = new CourseBase();
        //将dto中和courseBase属性名一样的属性值拷贝到courseBase中
        BeanUtils.copyProperties(dto,courseBase);
        //设置机构的id
        courseBase.setCompanyId(companyId);
        //创建时间
        courseBase.setCreateDate(LocalDateTime.now());
        //审核状态默认为未提交
        courseBase.setAuditStatus("202002");
        //发布状态默认为未发布
        courseBase.setStatus("203001");
        //向课程基本表插入一条记录
        int insert = courseBaseMapper.insert(courseBase);
        //获取课程id
        Long courseId = courseBase.getId();
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(dto,courseMarket);
        courseMarket.setId(courseId);
        //向课程营销基本表中插入一条记录
//        int insert1 = courseMarketMapper.insert(courseMarket);
        int insert1 = this.saveOrUpdateCourseMarket(courseMarket);
        if (insert <= 0 || insert1 <= 0){
            throw new RuntimeException("添加课程失败");
        }

        //组装要返回的结果
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(courseId);
        return courseBaseInfo;
    }

    /**
     * 根据课程id来查询课程的基本信息和营销信息
     * @param courseId 课程id
     * @return 课程的基本信息
     */
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId){

        //课程的基本信息
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        //课程的营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        //组装数据
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        if (courseMarket != null) {
            BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);
        }

        //根据课程分类的id查询分类的名称
        String mt = courseBase.getMt();
        String st = courseBase.getSt();

        CourseCategory mtCategory = courseCategoryMapper.selectById(mt);
        CourseCategory stCategory = courseCategoryMapper.selectById(st);

        if (mtCategory != null){
            //分类名称
            String mtName = mtCategory.getName();
            courseBaseInfoDto.setMtName(mtName);
        }
        if (stCategory != null){
            //分类名称
            String stName = stCategory.getName();
            courseBaseInfoDto.setStName(stName);
        }

        return courseBaseInfoDto;
    }


    /**
     * 修改课程的接口
     * @param courseBaseInfoDto
     * @return
     */
    @Override
    @Transactional
    public CourseBaseInfoDto modifyCourseBaseById(Long companyId ,CourseBaseInfoDto courseBaseInfoDto) {

        //进行数据的合法性校验--是否真正意义上存在该课程
        CourseBase selectById = courseBaseMapper.selectById(courseBaseInfoDto.getId());
        if (selectById == null){
            throw new XueChengPlusException("没有这门课程");
        }

        //进行业务逻辑的校验---本机构只能修改本机构的课程
        if (companyId != courseBaseInfoDto.getCompanyId()){
            throw new XueChengPlusException("本机构只能修改本机构的课程");
        }

        //创建课程基本信息表对象
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(courseBaseInfoDto,courseBase);
        courseBase.setChangeDate(LocalDateTime.now());
        //根据id修改课程基本信息表当中的内容
        int updateById = courseBaseMapper.updateById(courseBase);
        //创建课程营销表对象
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(courseBaseInfoDto,courseMarket);

        //数据校验--校验如果课程为收费，价格必须输入
//        String charge = courseMarket.getCharge();
//        if (charge.equals("201001")){//收费
//            if ((StringUtils.isBlank(courseMarket.getPrice() + "") || courseMarket.getPrice() == 0)){
//                XueChengPlusException.cast("此课程为收费，但是价格为空");
//            }
//        }

        //根据id修改课程营销表对象当中的内容---对于课程营销表当中的内容，我们有则更新，没有则添加
//        boolean saveOrUpdate = courseMarketService.saveOrUpdate(courseMarket);
        int saveOrUpdate = this.saveOrUpdateCourseMarket(courseMarket);
        if (updateById <= 0 || saveOrUpdate <= 0){
            throw new XueChengPlusException("修改课程失败");
        }
        //组装最后返回结果
        return courseBaseInfoDto;
    }

    //抽取对课程营销表的保存
    private int saveOrUpdateCourseMarket(CourseMarket courseMarket){

        //收费规则的数据校验
        String charge = courseMarket.getCharge();
        if (StringUtils.isBlank(charge)){
            throw new XueChengPlusException("收费规则没有选择！");
        }
        //数据校验--校验如果课程为收费，价格必须输入
        if (charge.equals("201001")){//收费
            if ((StringUtils.isBlank(courseMarket.getPrice() + "") || courseMarket.getPrice() == 0)){
                XueChengPlusException.cast("此课程为收费，但是价格为空");
            }
        }
        //保存到数据库
        boolean b = courseMarketService.saveOrUpdate(courseMarket);
        return b?1:0;
    }


    /**
     * 删除课程:删除课程相关的基本信息、营销信息、课程计划、课程教师信息
     * @param id
     * @param companyId
     */
    @Override
    @Transactional
    public void delCourseBase(Long id, Long companyId) {

        //首先进行数据的校验--本机构人员才能删除本机构的课程
        CourseBase courseBase = courseBaseMapper.selectById(id);
        Long companyId1 = courseBase.getCompanyId();
        if (companyId != companyId1){
            throw new XueChengPlusException("只允许本机构人员才能删除本机构的课程");
        } else {

            //再一次进行数据校验--课程的审核状态为未提交时方可删除
            CourseBase base = courseBaseMapper.selectById(id);
            //获取课程的审核状态
            String auditStatus = base.getAuditStatus();
            if (!auditStatus.equals("202002")){
                throw new XueChengPlusException("当前的课程状态不能被删除！");
            }
            //根据courseId删除course_base表
            courseBaseMapper.deleteById(id);
            //根据courseId删除course_market表
            courseMarketMapper.deleteById(id);
            //根据courseId删除course_teacher表
            LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CourseTeacher::getCourseId,id);
            courseTeacherMapper.delete(queryWrapper);
            //根据courseId删除teachplan表
            LambdaQueryWrapper<Teachplan> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Teachplan::getCourseId,id);
            teachplanMapper.delete(wrapper);
            //根据courseId删除teachplan_media表
            LambdaQueryWrapper<TeachplanMedia> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(TeachplanMedia::getCourseId,id);
            teachplanMediaMapper.delete(wrapper1);
        }

    }
}
